package foliotracker.controllers;

import java.util.ArrayList;
import java.util.List;

import foliotracker.Portfolio;
import foliotracker.Stock;
import foliotracker.views.ISellStockView;

public class SellStockController
{

	private ISellStockView view;
	private Portfolio portfolio;
	private String symbol;
	private int quantity;
	
	public SellStockController(Portfolio portfolio)
	{

		this.portfolio = portfolio;
	}
	
	public void setView(ISellStockView view)
	{
		this.view = view;
	}
	
	
	
	/**
	 * Gets the appropriate values from the view and then calls the sell method on the portfolio.
	 */
	public void sellStock()
	{
		portfolio.sellStock(symbol, quantity);
		
	}
	
	/**
	 * Checks that all the required values are present and correct; if they aren't, the relevant view.set...Error is called.
	 * @return True if the validation succeeded; otherwise, false.
	 */
	public boolean validate()
	{
		boolean success = true;
		
		symbol = view.getSymbol();
		
		try
		{
			quantity = Integer.parseInt(view.getQuantity());
			
			Stock stock = portfolio.getStockBySymbol(symbol);
			
			if (quantity > stock.getQuantity())
			{
				view.setQuantityError("Quantity greater than stock held");
				success = false;
			}
			else if (quantity < 1)
			{
				view.setQuantityError("Enter a value greater than 0");
				success = false;
			}
		}
		catch (NumberFormatException ex)
		{
			view.setQuantityError("Invalid integer");
			success = false;
		}
		
		return success;
	}

	public List<String> getSymbols()
	{
		List<String> symbols = new ArrayList<String>();
		
		for (Stock stock: portfolio.getStocks())
		{
			symbols.add(stock.getSymbol());
		}
		
		return symbols;
	}
}
